<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$data['banners'] = Banner::model()->findAll(array('order'=>"`order` ASC"));
		$data['series'] = Series::model()->findAllByAttributes(array('is_visible' => 1));
		$data['brands'] = Brand::model()->findAll();
		$data['mini'] = Banners::model()->findAll();

		$this->render('index', $data);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionAbout() {
		$this->render('about');
	}

	public function actionFaq() {
		$this->render('faq');
	}

	public function actionSupport() {
		$this->render('support');
	}

	public function actionMap() {
		$data['brands'] = Brand::model()->findAll();
		$data['cats'] = Category::model()->findAllByAttributes(array('parent_id' => 0));
		foreach ($data['cats'] as $cat) {
			$data['subcats'][$cat->id] = Category::model()->findAllByAttributes(array('parent_id' => $cat->id));
			$data['filters'][$cat->id] = Filter::model()->findAllByAttributes(array('category_id' => $cat->id));
		}
		$this->render('map', $data);
	}

	public function actionBrands() {
		if(Yii::app()->getRequest()->getQuery('category')) {
			$data['brands'] = Brand::model()->findAllByAttributes(array('category_id' => Yii::app()->getRequest()->getQuery('category')));
			$data['cat'] = Category::model()->findByPk(Yii::app()->getRequest()->getQuery('category'));
			$this->render('brands', $data);
		} else {
			$this->redirect(Yii::app()->homeUrl);
		}
	}

	public function actionCatalog() {
		if(Yii::app()->getRequest()->getQuery('category')) {
			if(Yii::app()->getRequest()->getQuery('filter')) {
				$request_filter = Yii::app()->getRequest()->getQuery('filter');
				$criteria = new CDbCriteria();
				$criteria->addSearchCondition('filter_id', $request_filter);
				$criteria->addSearchCondition('is_visible', 1);
				$count = Item::model()->count($criteria);
				$pages = new CPagination($count);
				$pages->pageSize = 12;

				if(Yii::app()->getRequest()->getQuery('page') && Yii::app()->getRequest()->getQuery('page') <= $pages->getPageCount())
					$pages->setCurrentPage(Yii::app()->getRequest()->getQuery('page'));

				$pages->applyLimit($criteria);

				$data['items'] = Item::model()->findAll($criteria);
				$data['curfilter'] = Filter::model()->findByPk($request_filter);

				$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/filter/'.$request_filter.'/';
			} else if(Yii::app()->getRequest()->getQuery('subcategory')) {
				$request_subcat = Yii::app()->getRequest()->getQuery('subcategory');
				$criteria = new CDbCriteria();
				$criteria->addSearchCondition('subcat_id', $request_subcat);
				$criteria->addSearchCondition('is_visible', 1);
				$count = Item::model()->count($criteria);
				$pages = new CPagination($count);
				$pages->pageSize = 12;
				if(Yii::app()->getRequest()->getQuery('page') && Yii::app()->getRequest()->getQuery('page') <= $pages->getPageCount())
					$pages->setCurrentPage(Yii::app()->getRequest()->getQuery('page'));

				$pages->applyLimit($criteria);

				$data['items'] = Item::model()->findAll($criteria);
				$data['cursubcategory'] = Category::model()->findByPk($request_subcat);

				$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/subcategory/'.$request_subcat.'/';
			} else if(Yii::app()->getRequest()->getQuery('brand')) {
				$request_cat = Yii::app()->getRequest()->getQuery('category');
				$request_brand = Yii::app()->getRequest()->getQuery('brand');
				$criteria = new CDbCriteria();
				$criteria->addSearchCondition('brand_id', $request_brand);
				$criteria->addSearchCondition('cat_id', $request_cat);
				$criteria->addSearchCondition('is_visible', 1);
				$count = Item::model()->count($criteria);
				$pages = new CPagination($count);
				$pages->pageSize = 12;

				if(Yii::app()->getRequest()->getQuery('page') && Yii::app()->getRequest()->getQuery('page') <= $pages->getPageCount())
					$pages->setCurrentPage(Yii::app()->getRequest()->getQuery('page'));

				$pages->applyLimit($criteria);

				$data['items'] = Item::model()->findAll($criteria);
				$data['curbrand'] = Brand::model()->findByPk($request_brand);

				$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/brand/'.$request_brand.'/';
			} else {
				$request_cat = Yii::app()->getRequest()->getQuery('category');
				$criteria = new CDbCriteria();
				$criteria->addSearchCondition('cat_id', $request_cat);
				$criteria->addSearchCondition('is_visible', 1);
				$count = Item::model()->count($criteria);
				$pages = new CPagination($count);
				$pages->pageSize = 12;

				
				if(Yii::app()->getRequest()->getQuery('page') && Yii::app()->getRequest()->getQuery('page') <= $pages->getPageCount())
					$pages->setCurrentPage(Yii::app()->getRequest()->getQuery('page') - 1);

				$pages->applyLimit($criteria);


				$data['items'] = Item::model()->findAll($criteria);
				$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/';
			}
			$data['pages'] = $pages;
			$data['category_id'] = Yii::app()->getRequest()->getQuery('category');
			$data['category'] = Category::model()->findByPk($data['category_id']);
			$data['filters'] = Filter::model()->findAllByAttributes(array('category_id' => $data['category_id']));
			$data['subcats'] = Category::model()->findAllByAttributes(array('parent_id' => $data['category_id']));
			$data['brands'] = Brand::model()->findAllByAttributes(array('category_id' => $data['category_id']));
			foreach ($data['items'] as $item) {
				$data['brand_item'][$item->id] = Brand::model()->findByPk($item->brand_id);
			}

			$this->render('catalog', $data);
		} else {
			$this->redirect(Yii::app()->homeUrl);
		}
	}

	public function actionSeries() {
		if(Yii::app()->getRequest()->getQuery('id')) {
			$data['items'] = array();
			$itemsinseries = ItemInSeries::model()->findAllByAttributes(array('series_id' => Yii::app()->getRequest()->getQuery('id')));
			foreach ($itemsinseries as $item) {
				array_push($data['items'], Item::model()->findByPk($item->item_id));
			}

			$data['series'] = Series::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
			$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/';
			$data['cats'] = Category::model()->findAllByAttributes(array('parent_id' => 0));

			$this->render('series', $data);
		} else {
			$this->redirect(Yii::app()->homeUrl);
		}
	}

	public function actionHot() {
		$criteria = new CDbCriteria;
		$criteria->condition = "is_visible = 1 AND (is_new = 1 OR discount > 0)";
		$data['items'] = Item::model()->findAll($criteria);

		$data['series'] = Series::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$data['url'] = '/site/catalog/category/'.Yii::app()->getRequest()->getQuery('category').'/';
		$data['cats'] = Category::model()->findAllByAttributes(array('parent_id' => 0));

		$this->render('hot', $data);
	}

	public function actionItem() {
		if(Yii::app()->getRequest()->getQuery('id')) {
			$model = Item::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
			if($model !== null) {
				$data['category_id'] = $model->cat_id;
				$data['brands'] = Brand::model()->findAll();
				$data['filters'] = Filter::model()->findAllByAttributes(array('category_id' => $data['category_id']));
				$data['subcats'] = Category::model()->findAllByAttributes(array('parent_id' => $data['category_id']));
				$data['curbrand'] = Brand::model()->findByPk($model->brand_id);
				$data['filter'] = Filter::model()->findByPk($model->filter_id);
				$data['category'] = Category::model()->findByPk($model->cat_id);
				$data['item'] = $model;

				$data['advice_item'] = Item::model()->findAllByAttributes(array('brand_id' => $model->brand_id, 'filter_id' => $model->filter_id));

				$this->render('item', $data);
			} else {
				$this->redirect(Yii::app()->homeUrl);
			}
		} else {
			$this->redirect(Yii::app()->homeUrl);
		}
	}

	public function actionSavetocart() {
		$ovalue = isset(Yii::app()->request->cookies['cart']) ? Yii::app()->request->cookies['cart']->value : '';
		$already_was = false;

		$value = '';
		$tok1 = strtok($ovalue, ';');
		$cart_items = array();
		while($tok1 !== false) {
			array_push($cart_items, $tok1);
			$tok1 = strtok(';');
		}
		foreach ($cart_items as $ci) {
			$tok2 = strtok($ci, ',');
			$item_id = $tok2;
			$tok2 = strtok(',');
			$item_q = $tok2;
			
			if($item_id == $_POST['id']) {
				$already_was = true;
				$value .= $item_id . ',' . (($item_q + $_POST['q'] > 10)?10:($item_q + $_POST['q'])) . ';';
			} else
				$value .= $item_id . ',' . $item_q . ';';
		}

		if(!$already_was) {
			$new_item = $_POST["id"] . ',' . (($_POST["q"] < 10)?$_POST["q"]:10) . ';';
			$temp = new CHttpCookie('cart', $value . $new_item);
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart'] = $temp;

			$cart_q = isset(Yii::app()->request->cookies['cart_q']) ? Yii::app()->request->cookies['cart_q']->value : 0;
			$temp = new CHttpCookie('cart_q', $cart_q + 1 );
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart_q'] = $temp;
		} else {
			$temp = new CHttpCookie('cart', $value);
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart'] = $temp;
		}

		$this->redirect(Yii::app()->request->baseUrl . '/site/cart/');
	}

	public function actionCart() {
		$cart_cookie = isset(Yii::app()->request->cookies['cart']) ? Yii::app()->request->cookies['cart']->value : '';
		$data['items'] = array();
		$tok1 = strtok($cart_cookie, ';');
		$cart_items = array();
		while($tok1 !== false) {
			array_push($cart_items, $tok1);
			$tok1 = strtok(';');
		}
		foreach ($cart_items as $ci) {
			$tok2 = strtok($ci, ',');
			$item_id = $tok2;
			$tok2 = strtok(',');
			$data['quantity'][$item_id] = $tok2;
			array_push($data['items'], Item::model()->findByPk($item_id));
		}
		$this->render('cart', $data);
	}

	public function actionDeleteFromCart() {
		if(Yii::app()->getRequest()->getQuery('id')) {
			$ovalue = isset(Yii::app()->request->cookies['cart']) ? Yii::app()->request->cookies['cart']->value : '';
			$deleted = false;
			$value = '';
			$tok1 = strtok($ovalue, ';');
			$cart_items = array();
			while($tok1 !== false) {
				array_push($cart_items, $tok1);
				$tok1 = strtok(';');
			}
			foreach ($cart_items as $ci) {
				$tok2 = strtok($ci, ',');
				$item_id = $tok2;
				$tok2 = strtok(',');
				$item_q = $tok2;
				
				if($item_id != Yii::app()->getRequest()->getQuery('id')) 
					$value .= $item_id . ',' . $item_q . ';';
				else $deleted = true;
			}
			if($deleted) {
				$cart_q = isset(Yii::app()->request->cookies['cart_q']) ? Yii::app()->request->cookies['cart_q']->value : 0;
				$temp = new CHttpCookie('cart_q', $cart_q - 1 );
				$temp->expire = time()+60*60*24*365;
				Yii::app()->request->cookies['cart_q'] = $temp;
			}
			$temp = new CHttpCookie('cart', $value);
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart'] = $temp;
		}
		$this->redirect(Yii::app()->request->baseUrl . '/site/cart/');
	}

	public function actionClearCart() {
		$temp = new CHttpCookie('cart_q', '');
		$temp->expire = time()+60*60*24*365;
		Yii::app()->request->cookies['cart_q'] = $temp;
		$temp = new CHttpCookie('cart', '');
		$temp->expire = time()+60*60*24*365;
		Yii::app()->request->cookies['cart'] = $temp;
		$this->redirect(Yii::app()->request->baseUrl . '/site/cart/');
	}

	public function actionPage() {
		if(Yii::app()->getRequest()->getQuery('id')) {
			$data['page'] = Page::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
			$this->render('page', $data);
		}
	}

	public function actionPublishOrder() {
		if(!Yii::app()->user->isGuest) {
			$cart_cookie = isset(Yii::app()->request->cookies['cart']) ? Yii::app()->request->cookies['cart']->value : '';
			$data['items'] = array();
			$tok1 = strtok($cart_cookie, ';');
			$cart_items = array();
			$price = 0;
			$count = 0;
			while($tok1 !== false) {
				array_push($cart_items, $tok1);
				$tok1 = strtok(';');
				$count++;
			}
			foreach ($cart_items as $ci) {
				$tok2 = strtok($ci, ',');
				$item_id = $tok2;
				$tok2 = strtok(',');
				$data['quantity'][$item_id] = $tok2;
				$record = Item::model()->findByPk($item_id);
				array_push($data['items'], $record);
				$price += $record->price * $tok2;
			}
			
			if($count > 0) {
				$order = new Order;
				$order->user_id = Yii::app()->user->getId();
				$order->status = 1;
				$order->order_date = date('Y-m-d');
				$order->price = $price;
				$order->save();

				foreach ($data['items'] as $item) {
					$iio = new ItemInOrder;
					$iio->order_id = $order->id;
					$iio->item_id = $item->id;
					$iio->quantity = $data['quantity'][$item->id];
					$iio->save();
				}
			}
			
			$temp = new CHttpCookie('cart_q', '');
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart_q'] = $temp;
			$temp = new CHttpCookie('cart', '');
			$temp->expire = time()+60*60*24*365;
			Yii::app()->request->cookies['cart'] = $temp;
		}
		$this->redirect(Yii::app()->request->baseUrl . '/site/orders/');
	}

	public function actionOrders() {
		if(!Yii::app()->user->isGuest) {
			
		} else {
			$this->redirect(Yii::app()->request->baseUrl);
		}
	}


	public function actionItemImage() {
		header('Content-type: image/png');
		$image = new SimpleImage(); 
		$image->load(getcwd() . $_GET['img']); 
		if($image->getWidth() > $image->getHeight())
			$image->resizeToWidth(200);
		else 
			$image->resizeToHeight(200);
		$image->output();
	}

	public function actionBrandImage() {
		header('Content-type: image/png');
		$image = new SimpleImage(); 
		$image->load(getcwd() . $_GET['img']); 
		if($image->getWidth() > $image->getHeight())
			$image->resizeToWidth(180);
		else 
			$image->resizeToHeight(180);
		$image->output();
	}

	public function actionSeriesImage() {
		header('Content-type: image/png');
		$image = new SimpleImage(); 
		$image->load(getcwd() . $_GET['img']); 
		if($image->getWidth() > $image->getHeight())
			$image->resizeToWidth(187);
		else 
			$image->resizeToHeight(187);
		$image->output();
	}

	public function actionCarouselImage() {
		header('Content-type: image/png');
		$image = new SimpleImage(); 
		$image->load(getcwd() . $_GET['img']); 
		if($image->getWidth() > $image->getHeight())
			$image->resizeToWidth(187);
		else 
			$image->resizeToHeight(187);
		$image->output();
	}
}